package cn.source.zk.service.impl;

import cn.source.authorizaton.domain.AuthorizedDevice;
import cn.source.authorizaton.service.IAuthorizedDeviceService;
import cn.source.common.core.domain.entity.SysRole;
import cn.source.common.utils.SecurityUtils;
import cn.source.system.domain.SystemInfo;
import cn.source.system.service.ICmsServiceItemService;
import cn.source.system.service.ISysRoleService;
import cn.source.system.service.ISysUserService;
import cn.source.zk.domain.entity.Channel;
import cn.source.zk.domain.entity.Device;
import cn.source.zk.domain.entity.DeviceDetails;
import cn.source.zk.domain.entity.Substation;
import cn.source.zk.domain.vo.DeviceChannelVO;
import cn.source.zk.domain.vo.DeviceSortVO;
import cn.source.zk.mapper.ZkAreaMapper;
import cn.source.zk.mapper.ZkDeviceMapper;
import cn.source.zk.mapper.ZkSubstationMapper;
import cn.source.zk.service.IZkAreaService;
import cn.source.zk.service.IZkChannelService;
import cn.source.zk.service.IZkDeviceDetailService;
import cn.source.zk.service.IZkDeviceService;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;


@Service
@Slf4j
public class ZkDeviceServiceImpl implements IZkDeviceService {

    @Autowired
    private ZkDeviceMapper deviceMapper;

    @Autowired
    private IZkDeviceDetailService deviceDetailService;

    @Autowired
    private ZkSubstationMapper substationMapper;

    @Autowired
    private IZkAreaService areaService;

    @Autowired
    private IZkChannelService channelService;

    @Autowired
    private ISysRoleService roleService;

    @Autowired
    private IAuthorizedDeviceService authorizedDeviceService;


    @Autowired
    private ICmsServiceItemService iCmsServiceItemService;


    /**
     * 获取设备主表分页列表
     *
     * @param device
     * @return
     */
    public List<Device> listPage(Device device) {

        //设置当前用户
        Substation substation = new Substation();
        substation.setCompanyId(SecurityUtils.getCompanyId());
        List<Substation> substationsList = substationMapper.selectListPage(substation);
        List<Long> substationsNumList = substationsList.stream().map(Substation::getNum).collect(Collectors.toList());

        return deviceMapper.selectListPage(device, substationsNumList);
    }




    @Override
    public Map<String, Object> getDeviceStats() {
        return deviceMapper.selectDeviceStats();
    }

    /**
     * 获取设备主表分页列表折叠列表
     *
     * @param device
     * @return
     */
    public List<DeviceChannelVO> listPageFold(Device device, List<Long> substationsNumList) {

        List<DeviceChannelVO> deviceChannelVOS = deviceMapper.selectListPageFold(device, substationsNumList, SecurityUtils.getUserId());

        for (DeviceChannelVO deviceChannelVO : deviceChannelVOS) {
            String ancestorName = areaService.getAncestorName(deviceChannelVO.getSubstation().getAreaNum());
            deviceChannelVO.getSubstation().setAncestorNames(ancestorName);


            ArrayList<Long> deviceNums = new ArrayList<>();
            deviceNums.add(deviceChannelVO.getNum());
            List<Channel> channels = channelService.getChannelListByDeviceNums(deviceNums);

            deviceChannelVO.setChannelList(channels);
        }

        return deviceChannelVOS;
    }

    @Override
    public List<Device> getByDevModel(List<Long> nums) {

        return deviceMapper.getByDevModel(nums);
    }

    @Override
    public List<Device> getBySubstationNums(List<Long> nums) {

        return deviceMapper.getBySubstationNums(nums);
    }

    @Override
    public List<Device> selectDeviceByNotAuth(Device device) {
        return deviceMapper.selectDeviceByNotAuth(device);
    }

    @Override
    public List<Device> getByDevNum(String devNum) {
        return deviceMapper.getByDevNum(devNum);
    }

    /**
     * 新增设备
     *
     * @param device
     * @return
     */
    @Transactional
    public int add(Device device) {
        //这里要考虑插入主表后返回主表的num，后需要插入到明细表中；
        device.setZhGuid(UUID.randomUUID().toString()); //设置设备ID
        //device.setDevStatus("0");//设置设备状态
        int result = deviceMapper.add(device);

        if (result > 0) {
            Long num = device.getNum();
            DeviceDetails deviceDetails = new DeviceDetails();
            deviceDetails.setDevId(num);
            // deviceDetails.setAccessMode("UDP方式");
            deviceDetails.setInstrumentNum("1");
            deviceDetails.setSerialPort("COM1");
            deviceDetails.setBaudRate("9600");
            deviceDetails.setDevPort("1050");
            deviceDetails.setDevIp("192.168.1.178");
            deviceDetails.setBackendPort("1000");
            deviceDetails.setBackendIp("192.168.1.122");
            deviceDetails.setDevMask("255.255.255.0");
            deviceDetails.setDevGw("192.168.1.1");
            deviceDetails.setTimeSyncMeth("0");
            deviceDetails.setWavePoint("205");
            // deviceDetails.setStorageInterval("60");
            int addCount = deviceDetailService.add(deviceDetails);
        }


        return result;
    }

    //    定时任务更新设备状态
    public void updateDevice() {
       //   修改没有通道数据的状态
        deviceMapper.updateDeviceNoDataStatus();
        //       修改2个小时内没有数据的状态
        deviceMapper.updateDeviceStatus();
    }

    /**
     * 根据num查询设备
     *
     * @param num
     * @return
     */
    public Device getByNum(Long num) {
        Device device = new Device();
        device.setNum(num);
        log.info("devNum,{}", device.getDevNum());
        //return deviceMapper.selectListPage(device,null).get(0);
        return deviceMapper.getByNum(num);
    }


    /**
     * 修改设备
     *
     * @param device
     * @return
     */
    public int edit(Device device) {
        AuthorizedDevice authorizedDevice = new AuthorizedDevice();
        authorizedDevice.setDeviceId(device.getNum());
        authorizedDevice.setUserId(SecurityUtils.getUserId());
        List<AuthorizedDevice> deviceList = authorizedDeviceService.selectAuthorizedDeviceList(authorizedDevice);
        if(deviceList.size() > 0 && SecurityUtils.getUserId() != 1) {
            throw new RuntimeException("被授权设备不能修改");
        }
        SystemInfo systemInfo = new SystemInfo();
        systemInfo.setUpdateflag("1");
        iCmsServiceItemService.updateSystemInfo(systemInfo);
        return deviceMapper.edit(device);
    }

    @Transactional
    public int removeBatch(List<Long> nums) {

        // 删除明细表的信息,根据devId删除明细表信息
        deviceDetailService.removeBatch(nums);

        return deviceMapper.removeBatch(nums);
    }

    /**
     * 批量修改设备状态
     *
     * @param zhGuids
     * @return
     */
    public int editBatchStates(List<String> zhGuids) {
        return deviceMapper.editBatchStated(zhGuids);

    }

    /**
     * 获取已有的设备排序
     *
     * @return
     */
    public List<DeviceSortVO> getSortList() {
        return deviceMapper.getSortList();
    }

    @Override
    public List<Device> selectLostSignalDevices() {
        return deviceMapper.selectLostSignalDevices();
    }
}
